import {
  AnimationClip,
  AnimationMixer,
  ColorKeyframeTrack,
  NumberKeyframeTrack,
  Quaternion,
  QuaternionKeyframeTrack,
  Vector3,
  VectorKeyframeTrack,
} from 'three'

// 创建动画轨道
// 位置
const positionKF = new VectorKeyframeTrack(
  '.position', //动画对应属性名
  [0, 1, 2, 3, 4], //动画帧数组
  [50, 50, 50, 50, 50, -50, -50, 50, -50, -50, 50, 50, 50, 50, 50] //动画位置数组position对应[x,y,z],数组中每三个一组
)
// 缩放
const scaleKF = new VectorKeyframeTrack(
  '.scale',
  [0, 1, 2, 3, 4],
  [1, 1, 1, 2, 2, 2, 1, 1, 1, 2, 2, 2, 1, 1, 1] //动画位置数组position对应[x,y,z],数组中每三个一组
)
// 旋转
const xAxis = new Vector3(1, 0, 0)
const qInitial = new Quaternion().setFromAxisAngle(xAxis, 0)
const qFinal = new Quaternion().setFromAxisAngle(xAxis, Math.PI)
const quaternionKF = new QuaternionKeyframeTrack(
  '.quaternion',
  [0, 1, 2, 3, 4], //动画帧数组
  [
    qInitial.x,
    qInitial.y,
    qInitial.z,
    qInitial.w,
    qFinal.x,
    qFinal.y,
    qFinal.z,
    qFinal.w,
    qInitial.x,
    qInitial.y,
    qInitial.z,
    qInitial.w,
    qFinal.x,
    qFinal.y,
    qFinal.z,
    qFinal.w,
    qInitial.x,
    qInitial.y,
    qInitial.z,
    qInitial.w,
  ]
)

// 颜色
const colorKF = new ColorKeyframeTrack(
  '.material.color',
  [0, 1, 2, 3, 4],
  [1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0] //动画颜色数组对应[r,g,b],数组中每三个一组0-1对应0-255
)
const opacityKF = new NumberKeyframeTrack(
  '.material.opacity',
  [0, 1, 2, 3, 4],
  [1, 0, 1, 0, 1]
)

// 创建动画轨道集
const clip = new AnimationClip(
  'Action', //集名称
  4, //动画时间
  [positionKF, scaleKF, quaternionKF, colorKF, opacityKF] //动画集数组
)

export function enableAnimation(object, playable) {
  if (!playable) return
  // 动画管理
  const mixer = new AnimationMixer(object)
  const clipAction = mixer.clipAction(clip)
  clipAction.play()
  return mixer
}
